<?php
namespace app\admin\controller;

use app\common\controller\Auth;
use app\common\controller\AdminBase;
use think\Db;
use think\Session;

/**
 * 权限组
 * Class AuthGroup
 * @package app\admin\controller
 */
class AuthGroup extends AdminBase
{
    protected $auth_group_model;
    protected $auth_rule_model;

    protected function _initialize()
    {
        parent::_initialize();
        $this->auth_group_model = model('AuthGroup');
        $this->auth_rule_model  = model('AuthRule');
    }

    /**
     * 权限组
     * @return mixed
     */
    public function index()
    {
        $auth_group_list = $this->auth_group_model->select();

        /*合同签订公司*/
        $sign_company_list = logic('Contract')->getSignCompanyList();
        $sign_company_list_by_code = [];
        foreach ($sign_company_list as $v) {
            $sign_company_list_by_code[$v['code']] = $v['sign_company'];
        }

        return $this->fetch('index', [
            'auth_group_list' => $auth_group_list,
            'sign_company_list_by_code' => $sign_company_list_by_code,
        ]);
    }

    /**
     * 添加权限组
     * @return mixed
     */
    public function add()
    {
        /*合同签订公司*/
        $sign_company_list = logic('Contract')->getSignCompanyList();

        //dump($menu);exit;
        if ($this->request->isAjax()) {
            $data = $this->request->post();

            //获取选中的ids
            if (!empty($data['rules'])) {
                $ids = $data['rules'];//被选中的规则id，数组
                $ids = array_unique(array_filter(array_map(function ($v){
                    return (int)$v;
                }, $ids)));
                $data['rules'] = implode(',', $ids);//重新拼凑成，分割的数据
            } else {
                //$data['rules'] = '';
                return ajax_return_error('请为角色指定权限！');
            }

            if (empty($data['title'])) {
                return ajax_return_error('角色名称必须填写！');
            }

            if (empty($data['code']) || !in_array($data['code'], array_column($sign_company_list, 'code'))) {
                $data['code'] = '';
            }

            $group_info = $this->auth_group_model->getInfo(['title' => $data['title']], 'title');
            if (!empty($group_info)) {
                return ajax_return_error('角色已经存在！');
            }

            $auth_group_id = $this->auth_group_model->addData($data);
            if ($auth_group_id !== false) {
                return ajax_return_adv('保存成功');
            } else {
                return ajax_return_error('保存失败');
            }
        }

        return $this->fetch('add', [
            'menu' => $this->getMenuTree(),
            'sign_company_list' => $sign_company_list,
        ]);
    }

    /**
     * 获取权限（菜单）结构数据
     * @return array|bool
     */
    private function getMenuTree()
    {
        $menu     = [];
        $admin_id = Session::get('admin_id');
        $auth     = new Auth();

        $auth_rule_list = Db::name('AuthRule')->field('id,pid,title,name')->order(['sort' => 'DESC', 'id' => 'ASC'])->select();

        foreach ($auth_rule_list as $value) {
            if (($value['pid'] == 0 && substr($value['name'], -7) == 'default') || $auth->check($value['name'], $admin_id) || $admin_id == 1) {
                $menu[] = $value;
            }
        }
        $menu = !empty($menu) ? array2tree($menu) : [];
        return $menu;
    }


    /**
     * 编辑权限组
     * @return mixed
     */
    public function edit()
    {
        $id = $this->request->param('id', 0, 'intval');

        /*合同签订公司,超级管理员不用选择*/
        if ($id > 1) {
            $sign_company_list = logic('Contract')->getSignCompanyList();
        } else {
            $sign_company_list = [];
        }

        $auth_group = $this->auth_group_model->find($id);

        if ($this->request->isAjax()) {
            $data = $this->request->post();

            //获取选中的ids
            if (!empty($data['rules'])) {
                $ids = $data['rules'];//被选中的规则id，数组
                $ids = array_unique(array_filter(array_map(function ($v){
                    return (int)$v;
                }, $ids)));
                $data['rules'] = implode(',', $ids);//重新拼凑成，分割的数据
            } else {
                //$data['rules'] = '';
                return ajax_return_error('请为角色指定权限！');
            }

            if ($id == 1 || empty($data['code']) || !in_array($data['code'], array_column($sign_company_list, 'code'))) {
                $data['code'] = '';
            }

            if ($id == 1 && $data['status'] != 1) {
                return ajax_return_error('超级管理组不可禁用');
            }

            if ($this->auth_group_model->saveDate($id, $data) !== false) {
                return ajax_return_adv('更新成功');
            } else {
                return ajax_return_adv_error('更新失败');
            }
        }

        return $this->fetch('edit', [
            'auth_group' => $auth_group,
            'menu' => $this->getMenuTree(),
            'rules' => explode(',', $auth_group->rules),
            'sign_company_list' => $sign_company_list,
        ]);
    }


    /**
     * 删除权限组
     */
    public function delete()
    {
        $id = $this->request->param('id', 0, 'intval');
        if ($id > 0 && $this->request->isAjax()) {
            if ($id == 1) {
                return ajax_return_error('超级管理组不可删除');
            }

            if ($this->auth_group_model->destroy($id)) {
                return ajax_return_adv('删除成功');
            } else {
                return ajax_return_error('删除失败');
            }
        }
    }

    /**
     * 授权
     * @param $id
     * @return mixed
     */
    public function auth($id)
    {
        return $this->fetch('auth', ['id' => $id]);
    }


    /**
     * AJAX获取规则数据
     * @param $id
     * @return mixed
     */
    public function getJson($id)
    {
        $auth_group_data = $this->auth_group_model->find($id)->toArray();
        $auth_rules      = explode(',', $auth_group_data['rules']);
        $auth_rule_list  = $this->auth_rule_model->field('id,pid,title')->select();

        foreach ($auth_rule_list as $key => $value) {
            in_array($value['id'], $auth_rules) && $auth_rule_list[$key]['checked'] = true;
        }

        return $auth_rule_list;
    }


    /**
     * 更新权限组规则
     * @param $id
     * @param $auth_rule_ids
     */
    public function updateAuthGroupRule($id, $auth_rule_ids = '')
    {
        if ($this->request->isPost()) {
            if ($id) {
                $group_data['id']    = $id;
                $group_data['rules'] = is_array($auth_rule_ids) ? implode(',', $auth_rule_ids) : '';

                if ($this->auth_group_model->save($group_data, $id) !== false) {
                    $this->success('授权成功');
                } else {
                    $this->error('授权失败');
                }
            }
        }
    }

}